import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { UserControlApiService } from 'src/app/api/user-control-api.service';
import { startOfWeek, startOfMonth } from 'date-fns';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [UserControlApiService]
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  passwordVisible: boolean;
  date = new Date();
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private loginApi: UserControlApiService,

  ) {
    this.loginForm = fb.group(
      {
        username: [null, [Validators.required]],
        password: [null, [Validators.required]]
      }
    );
  }

  ngOnInit(): void {

    const firstDayOfWeek = startOfWeek(startOfMonth(new Date()), { weekStartsOn: 2 });
    console.log(firstDayOfWeek.toISOString());
  }

  loging(): void {
    // tslint:disable-next-line: forin
    for (const key in this.loginForm.controls) {
      this.loginForm.controls[key].markAsDirty();
      this.loginForm.controls[key].updateValueAndValidity();
    }
    if (this.loginForm.valid) {
      this.loginApi.login(this.loginForm.value).subscribe(
        respone => {
          localStorage.setItem('token', respone.tokenHead.concat(respone.token));
          this.router.navigateByUrl('/home');
        }
      );
    }
  }

  regsit(e: MouseEvent): void {
    e.preventDefault();
    this.router.navigateByUrl('/regist');
  }

}
